use actix_web::{http::StatusCode, web, HttpRequest, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

pub fn set_routes(cfg: &mut web::ServiceConfig) {
    cfg.route("/", web::get().to(index))
        .route("/login", web::post().to(login));
}

async fn index() -> impl Responder {
    HttpResponse::Ok().body("authentication_controller")
}

#[derive(Debug, Serialize, Deserialize)]
struct LoginParam {
    username: String,
    password: String,
    #[serde(rename(serialize = "deviceInfo", deserialize = "deviceInfo"))]
    device_info: Value,
    #[serde(rename(serialize = "systemInfo", deserialize = "systemInfo"))]
    system_info: Value,
}

async fn login(param: web::Json<LoginParam>, req: HttpRequest) -> impl Responder {
    println!("{:?}", param);

    let error_code = "";

    // All response data format is for the client which works with spring security rest.
    if error_code.is_empty() {
        return super::shared::get_data_response(json!({}));
    } else {
        super::shared::get_error_response(
            StatusCode::UNAUTHORIZED,
            "error",
            error_code,
            req.uri().to_string().as_str(),
        )
    }
}
